/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;


import java.util.concurrent.ConcurrentHashMap;

/**
 * the main data storage structure. references to the same pool will be stored
 * twice. Once in the list of all polls (polls), the second time into a list
 * of polls of the given "admin" : identified by his e-mail address.
 * 
 * By now, only the storage in the list of all polls is implemented.
 */
public class PollList {
    private long pollCounter = 0;
    
    ConcurrentHashMap<Long, Poll> polls = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, ConcurrentHashMap<Integer, Poll> > pollsByAdmin = new ConcurrentHashMap<>();
    
    boolean addVote(VoteInterface vote, StringBuilder errorMessage) {
        long pollId = vote.getPollId();
        Poll poll;
        synchronized (this){
            poll = polls.get(pollId);
        }
        
        if(poll == null) {
            errorMessage.append("Poll doesn't exist (" + pollId + ")");
            return false;
        }
        
        return poll.addVote(vote, errorMessage);
    }
    
    /**
     * creating a poll with the given arguments and automatically adding it
     * to the data storage structure. A reference to the poll is returned.
     * 
     * The poll id is generated automatically and assigned to the returned poll
     * @param options list containing the possible options for this poll
     * @param emailAddress address of the administrator.
     * @return 
     */
    public synchronized Poll createPoll(String[] options, String emailAddress){
        Poll poll = new Poll(pollCounter,options,emailAddress);
        this.polls.put(pollCounter, poll);
        //this.pollsByAdmin
        pollCounter++;
        return poll;
    }
  
    public synchronized Poll getPoll(long id){
        return polls.get(new Long(id));
    }

}
